import NormalFilter from 'components/Filter/NormalFilter'
import LwjTable from 'components/LwjTable/LwjTable'
import { Button, Modal, Switch, Divider, Popover, message } from 'antd'
import { Loader } from 'components'
import lodash from 'lodash'
//时间转化
import moment from 'moment'
//样式
import styles from './StoreList.less'


const ProductsModal = ({ location, dispatch, store, cates, originCates, toggleModal, app, loading }) => {

  // 弹窗数据
  const storeFilterProps = {
    filterItems: [
      {
        type: 'input',
        id: 'name',
        title: '商品名称'
      },
      {
        type: 'treeSelect',
        id: 'cateIdAndChilds',
        title: '商品分类',
        options: cates,
        checkable: true,
        maxTagCount: 1,
        searchPlaceholder: "请选择"
      },
      {
        type: 'input',
        id: 'goods_id',
        title: 'SPU编码'
      }, {
        type: 'input',
        id: 'id',
        title: 'SKU编码'
      }
    ],
    Col: 8,
    isExpand: true,
    onFilterChange(value) {
      let _temp = lodash.cloneDeep(value);
      if (value.cateIdAndChilds) {
        _temp.cateIdAndChilds = [];
        value.cateIdAndChilds.map(val => {
          _temp.cateIdAndChilds.push(val.split('-').pop() - 0);
        })
      }
      dispatch({
        type: 'storelist/changeParam',
        queryParam: _temp
      })
      dispatch({
        type: 'storelist/productList',
        payload: {
          start: 0,
          limit: store.pagination.pageSize
        }
      })
    }
  }

  // 表格属性
  const productTableProps = {
    dataSource: store.list,
    loading: loading.effects['productlist/productList'],
    pagination: store.pagination,
    pageChangeAction: 'storelist/productList',
    dispatch,
    location,
    rowSelection: {
      onChange: (selectedRowKeys, selectedRows) => {
        dispatch({
          type: 'storelist/setSelectedRows',
          selectedRowKeys: selectedRowKeys,
          selectedRows: selectedRows
        })
      },
      getCheckboxProps: record => ({
        disabled: !record.has_material, // Column configuration not to be checked
        name: record.id.toString(),
      }),
      selectedRowKeys: store.selectedRowKeys
    }
  };

  const productsColumns = [
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
      width: '20%'
    }, {
      title: '商品图片',
      dataIndex: 'goods_info',
      key: 'goods_info',
      width: '15%',
      render: (text, record) => {
        return (
          <Popover content={<img src={record.goods_info ? record.goods_info.cover_path : ''} className={styles.productBigImg} />} title="商品图片" placement="right">
            <img src={record.goods_info ? record.goods_info.cover_path : ''} className={styles.productSmallImg} />
          </Popover>
        )
      }
    }, {
      title: '商品分类',
      dataIndex: 'cate_name',
      key: 'cate_name',
      width: '10%'
    }, {
      title: 'SPU',
      dataIndex: 'goods_id',
      key: 'goods_id',
      width: '10%'
    }, {
      title: 'SKU',
      dataIndex: 'sku_id',
      key: 'sku_id',
      width: '10%'
    }, {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      width: '8%'
    }, {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '10%',
      render: (text, record) => {
        return (
          <span>{record.isLinked ? '已关联' : '未关联'}</span>
        )
      }
    },  {
      title: '建议零售价',
      dataIndex: 'price',
      key: 'price',
      width: '7%',
      render : (text) => text && text.toFixed(2)
    }, {
      title: '关联',
      key: 'handle',
      width: '10%',
      render: (text, record) => {
        if (record.has_material) {
          return (<Switch checkedChildren="是" unCheckedChildren="否" onChange={(value) => onChangeProduct(value, [record])} checked={record.isLinked} />)
        } else {
          return (<span>商品未绑定物料</span>)
        }
      }
    }
  ]

  const onChangeProduct = (value, record, flag) => {
    if (record && record.length == 0) {
      message.error("请选择" + (value ? '关联' : '取消关联') + "商品项");
      return;
    }
    let _temp = record.filter((item) => item.isLinked != value).map((item) => item.id);
    if (_temp && _temp.length > 0) {
      dispatch({
        type: 'storelist/link',
        param: {
          commodityIds: _temp,
          distributorIds: [store.id],
          linkedStatus: (value ? 'LINK' : 'CANCEL')
        },
        flag
      })
    } else {
      message.error("选择的商品项已" + (value ? '关联' : '取消关联'));
    }
  }

  const onChangeAllProduct = (flag) => {
    let cateIds = store.queryParam.cateIdAndChilds;
    let props = {
      title: '提示',
      content: '是否' + (flag ? '关联' : '取关') + '所有商品？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'storelist/alllink',
          params: {
            distributorId: [store.id],
            cateIdAndChilds: cateIds ? cateIds : null,
            linkedStatus: (flag ? 'bind' : 'cancel')
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    }
    if (cateIds) {
      let _temp = [];
      originCates.forEach((val) => {
        if (cateIds.indexOf(val.id) > -1) {
          _temp.push(val.name)
        }
      })
      props.content = '是否' + (flag ? '关联"' : '取关"') + _temp.join(',') + '"分类的全部商品？'
    }
    Modal.confirm(props)
  }

  const handleFormChange = (changedFields = {}) => {
    let queryParam = {};
    for (let key in changedFields) {
      queryParam[key] = changedFields[key].value
    }
    let _temp = lodash.cloneDeep(queryParam);
    if (queryParam.cateIdAndChilds) {
      _temp.cateIdAndChilds = [];
      queryParam.cateIdAndChilds.map(val => {
        _temp.cateIdAndChilds.push(val.split('-').pop() - 0);
      })
    }
    dispatch({
      type: 'storelist/changeParam',
      queryParam: _temp
    })
  }

  return (
    <Modal
      visible={store.modalVisible}
      title="商品池"
      onOk={() => toggleModal(false)}
      onCancel={() => toggleModal(false)}
      width={950}
      destroyOnClose={true}
      footer={[
        <Button key="back" onClick={() => toggleModal(false)}>关闭</Button>,
      ]}>
      <NormalFilter {...storeFilterProps} onChange={handleFormChange} />
      <div className={styles.productFilterBtnGap}>
        <Button type="primary" onClick={() => onChangeProduct(true, store.selectedRows, 'multiple')}>批量关联</Button>
        <Button type="primary" onClick={() => onChangeProduct(false, store.selectedRows, 'multiple')}>批量取关</Button>
        <Button type="primary" onClick={() => onChangeAllProduct(true)}>全部关联</Button>
        <Button type="primary" onClick={() => onChangeAllProduct(false)}>全部取关</Button>
      </div>
      <LwjTable {...productTableProps} columns={productsColumns} />
      <Loader spinning={loading.effects['storelist/link', 'storelist/alllink']} />
    </Modal>
  )
}

export default ProductsModal;
